/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.aries.ui.impl;

import com.aries.ui.view.viewgroup.View;

import ohos.agp.components.Component;

import ohos.multimodalinput.event.TouchEvent;

/**
 * {@link View}的实现类，所有实现逻辑均转发至此类。
 */
public class ViewImpl implements View {
    private final Component component;
    private boolean consumed;

    /**
     * 查看实现
     * @param component Component
     */
    public ViewImpl(Component component) {
        this.component = component;
    }

    /**
     * 调度触摸事件
     * @param event 被传递的触摸事件
     * @return 调度触摸事件
     */
    @Override
    public boolean dispatchTouchEvent(TouchEvent event) {
        boolean result = false;

        final int action = event.getAction();
        if (action == TouchEvent.PRIMARY_POINT_DOWN) {
            // Defensive cleanup for new gesture
            stopNestedScroll();
            consumed = false;
        }

        if (onTouchEvent(event)) {
            consumed = true;
            result = true;
        } else {
            consumed = false;
        }

        // Clean up after nested scrolls if this is the end of a gesture;
        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
        // of the gesture.
        if (action == TouchEvent.PRIMARY_POINT_UP ||
                action == TouchEvent.CANCEL ||
                (action == TouchEvent.PRIMARY_POINT_DOWN && !result)) {
            stopNestedScroll();
        }
        return result;
    }

    /**
     * 触摸事件
     * @param event 待消费的事件
     * @return 触摸事件
     */
    @Override
    public boolean onTouchEvent(TouchEvent event) {
        if (component instanceof View) return ((View) component).onTouchEvent(event);
        return false;
    }

    /**
     *  被消耗
     * @return 被消耗
     */
    @Override
    public boolean isConsumed() {
        boolean result = consumed;
        consumed = false;
        return result;
    }

    private void stopNestedScroll() {}
}
